package ishaportalunittests.helpers;

import static org.junit.Assert.assertTrue;
import gwtappcontainer.server.apis.admin.AdminAPI;
import gwtappcontainer.server.apis.admin.Roles.Role;
import gwtappcontainer.shared.apis.APIResponse;
import gwtappcontainer.shared.apis.APIResponse.Status;
import gwtappcontainer.shared.apis.admin.UserProp;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserServiceFactory;


public class APITestHelperTest {
	private final APITestHelper helper = new APITestHelper();
	
	@Before
	public void setUp() {
		helper.setUp();
	}
	
	@After 
	public void tearDown() {
		helper.tearDown();
	}
	
	@Test
	public void canLoginAsDeveloper() {
						
		AdminAPI api = new AdminAPI();
		User user = helper.loginAsDeveloper();
		
		APIResponse resp = api.getRolesForLoggedInUser(user);
		assertTrue(resp.statusCode == Status.SUCCESS);
		
		UserProp prop = (UserProp) resp.object;
		
		assertTrue(null != prop);
		assertTrue(null != prop.roles);
		
		assertTrue(Util.isRolePresent(prop.roles, Role.DEVELOPER.toString()));						
	}	
	
	@Test
	public void canLoginAsPortalAdmin() {
						
		AdminAPI api = new AdminAPI();
		User user = helper.loginAsPortalAdmin();
		
		APIResponse resp = api.getRolesForLoggedInUser(user);
		assertTrue(resp.statusCode == Status.SUCCESS);
		
		UserProp prop = (UserProp) resp.object;
		
		assertTrue(null != prop);
		assertTrue(null != prop.roles);
		
		assertTrue(Util.isRolePresent(prop.roles, Role.PORTAL_ADMIN.toString()));						
	}
	
	@Test
	public void canLoginAsPortalUser() {
		
		AdminAPI api = new AdminAPI();
		
		User user = helper.loginAsPortalUser();								
		APIResponse resp = api.getRolesForLoggedInUser(user);
		assertTrue(resp.statusCode == Status.SUCCESS);
		
		UserProp prop = (UserProp) resp.object;
		
		assertTrue(null != prop);
		assertTrue(null != prop.roles);
		
		assertTrue(Util.isRolePresent(prop.roles, Role.PORTAL_USER.toString()));						
	}
	
	@Test
	public void canLoginAsPortalReadonly() {
						
		AdminAPI api = new AdminAPI();
		User user = helper.loginAsPortalReadOnly();
		
		APIResponse resp = api.getRolesForLoggedInUser(user);
		assertTrue(resp.statusCode == Status.SUCCESS);
		
		UserProp prop = (UserProp) resp.object;
		
		assertTrue(null != prop);
		assertTrue(null != prop.roles);
		
		assertTrue(Util.isRolePresent(prop.roles, Role.PORTAL_READONLY.toString()));						
	}
	
	@Test
	public void canLoginAsAnyEmail() {
						
		String email = "test@example.com";
		User user = helper.loginAs(email);
		
		assertTrue(user.getEmail().equals(email));
	}
	
	@Test 
	public void canLogout() {
		helper.logout();
		User user = UserServiceFactory.getUserService().getCurrentUser();
		assertTrue(null == user);
		
	}		
}
